/**
 * Created by seikann on 2017-10-10.
 */
// 引入编写好的api
const api = require('./apis/commonApi');
// 引入文件模块
const fs = require('fs');
// 引入处理路径的模块
const path = require('path');
// 引入处理post数据的模块
const bodyParser = require('body-parser');
// 引入Express
const express = require('express');
const app = express();
//引入session模块
const cookieParser = require("cookie-parser");
const session = require("express-session");

app.use(cookieParser('123456'));
app.use(session({
  secret: '123456',
  cookie: {maxAge: 60 * 1000 * 10},
  resave: false,
  saveUninitialized: true
}));

app.use(function (req, res, next) {
  res.locals.user = req.session.user;   // 从session 获取 user对象
  // console.log(req)
  var err = req.session.error;   //获取错误信息
  delete req.session.error;
  res.locals.message = "";   // 展示的信息 message
  if (err) {
    res.locals.message = err;
  }
  next();  //中间件传递
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

for (let val in api) {
  app.use(api[val]);
}

// 访问静态资源文件 这里是访问所有dist目录下的静态资源文件
app.use(express.static(path.resolve(__dirname, '../dist')));
// 因为是单页应用 所有请求都走/dist/index.html
app.get('*', function (req, res) {
  const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8');
  res.send(html);
});
// 监听8888端口
app.listen(8888);
console.log('success listen………8888…');
